package com.example.zx_springboot.controller;


import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;

import com.example.zx_springboot.entity.Zxfiles;

import com.example.zx_springboot.mapper.Zx_FilesMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.beans.factory.annotation.Value;

import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import cn.hutool.core.io.FileUtil;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
@CrossOrigin(origins = "http://localhost:8080") // 允许来自 http://localhost:3000 的请求
@RestController
@RequestMapping("/file")

public class ZxFilesController {
    @Value("${files.upload.path}")
    private String uploadPath;
    @Autowired
    private Zx_FilesMapper zx_filesMapper;
    @PostMapping("/upload")
    public String upload(@RequestParam MultipartFile file) throws IOException {
        String originalFilename = file.getOriginalFilename();
        String type = FileUtil.extName(originalFilename);
        Long size = file.getSize();

        // 先存储到磁盘
        File uploadParentFile = new File(uploadPath);// 判断配置的文件目录是否存在，若不存在则创建一个新的文件目录
        if (!uploadParentFile.exists()) {

            uploadParentFile.mkdirs();
        }


        // 定义一个文件唯一的标识码
        String uuid = IdUtil.fastSimpleUUID();
        String fileUUID=uuid + StrUtil.DOT + type;
        File uploadFile = new File(uploadPath +fileUUID );
        //把获取到的文件存储到磁盘目录
        file.transferTo(uploadFile);
        //存储数据库
        String url = "http://localhost:8887/api/file/" + fileUUID;
        Zxfiles saveFile = new Zxfiles();
        saveFile.setName(originalFilename);
        saveFile.setType(type);
        saveFile.setUrl(url);
       zx_filesMapper.upload(saveFile);
        return url;

    }
    @GetMapping("/{fileUUID}")
    public void download(@PathVariable String fileUUID, HttpServletResponse response) throws IOException {
        // 根据文件的唯一标识码获取文件
        File uploadFile = new File(uploadPath + fileUUID);

        // 设置输出流的格式
        ServletOutputStream os = response.getOutputStream();

        // 设置Content-Disposition为inline
        response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(fileUUID, "UTF-8"));

        response.setContentType("image/png");


        // 读取文件的字节流
        os.write(FileUtil.readBytes(uploadFile));
        os.flush();
        os.close();
    }
}
